package com.gbase8c.dmt.db.opengauss;

import com.gbase8c.dmt.db.object.SchemaObject;

import com.gbase8c.dmt.model.migration.dto.DataSourceDto;
import com.gbase8c.dmt.model.migration.dto.SchemaDto;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import java.util.List;
import java.util.Map;

@Slf4j
public class SchemaObjectImpl extends MetaImpl implements SchemaObject {

    public SchemaObjectImpl(DataSourceDto dataSourceDto) {
        super(dataSourceDto);
    }
    public static List<String> sysDbNames = Lists.newArrayList("pg_toast", "cstore", "pkg_service", "dbe_perf", "snapshot", "blockchain",
            "pg_catalog", "public", "sqladvisor", "dbe_pldebugger", "dbe_pldeveloper", "information_schema", "db4ai",
            "dbms_output", "dbms_utility", "utl_file", "dbms_random", "oracle", "dbms_pipe", "dbms_alert", "plvdate", "plvstr", "plvchr",
            "plvsubst", "plunit", "plvlex", "dbms_assert", "orafce", "compat_tools", "dbms_metadata", "dbms_job", "dbms_lock", "dbms_application_info",
            "dbms_obfuscation_toolkit", "utl_url", "utl_encode", "utl_raw", "dbms_lob", "wmsys", "gha");

    @Override
    public List<String> getNames(Map<String, Object> params) {
        String sql = "SELECT nspname FROM pg_namespace";
        return query(sql, new ColumnListHandler<String>());
    }

    @Override
    public SchemaDto get(String name, Map<String, Object> params) {
        return null;
    }

    @Override
    public SchemaDto convert(SchemaDto schemaDto, Map<String, Object> params) {
//        boolean preserveCase = schemaDto.getTask().getMigrateConfig().isPreserveCase();
//        if (preserveCase) {
//            schemaDto.setTarName(schemaDto.getName());
//        } else {
//            schemaDto.setTarName(schemaDto.getName().toLowerCase());
//        }
        schemaDto.setConvertible(Boolean.TRUE);
        return schemaDto;
    }

    @Override
    public String sql(SchemaDto schemaDto, Map<String, Object> params) {
        StringBuilder sb = new StringBuilder();
        String tarSchemaName = schemaDto.getTarName();
        boolean preserveCase = schemaDto.getTask().getMigrateConfig().isPreserveCase();
            sb.append("CREATE SCHEMA ").append(wrap(tarSchemaName, true)).append(";").append("\r\n");
        log.info(String.valueOf(sb));
        return sb.toString();
    }

    @Override
    public List<String> getNames(Map<String, Object> params, boolean includeSystemSchemas) {
        String sql = "select schema_name from information_schema.schemata";
        List<String> schemaNames = query(sql,new ColumnListHandler<>());
        if (!includeSystemSchemas) {
            schemaNames.removeAll(sysDbNames);
        }
        return schemaNames;
    }
}
